<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item label="产品类型">
        <el-input
          v-model="queryParams.categoryNum"
          placeholder="请输入产品类型"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型名称">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入类型名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="分类状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          v-hasPermi="['product:category:query']"
        >搜索
        </el-button>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:category:add']"
          v-show="false"
        >新增
        </el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" v-hasPermi="['product:category:export']"
                   @click="handleExport"
        >导出
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading" border
      :data="productCategoryTree"
      row-key="categoryId"
      :default-expand-all="true"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="categoryNum" label="产品类型" width="200"/>
      <el-table-column prop="categoryName" label="类型名称"/>
      <el-table-column prop="categoryName" label="强弱电类型" width="120" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.onlineType==='1'">
            <el-tag type="danger">强电</el-tag>
          </template>
          <template v-else-if="scope.row.onlineType==='2'">
            <el-tag>弱电</el-tag>
          </template>
          <template v-else>
            <el-tag type="info">未知</el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" label="排序" width="50" align="center"/>
      <el-table-column prop="status" label="状态" :formatter="statusFormat" align="center" width="80"/>
      <el-table-column label="功能" width="200" v-if="false">
        <template slot-scope="scope">
          <el-row>
            <el-col v-for="(item) in scope.row.dictLabelList" :span="8" style="margin-top: 5px">
              <el-tag>{{ item }}</el-tag>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="200" v-if="false"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dept:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['product:category:add']"
          >新增
          </el-button>
          <el-button
            v-if="scope.row.parentId !== 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:category:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改产品类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body :before-close="closeDialogConfirm">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级分类" prop="parentId">
              <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级分类"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类编号" prop="categoryNum">
              <el-input v-model="form.categoryNum" placeholder="请输入分类编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="categoryName">
              <el-input v-model="form.categoryName" placeholder="请输入分类名称"/>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="产品功能" prop="function" v-if="false">
              <el-select v-model="selectedDictList" multiple placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in productFunctionOptions"
                  :key="item.dictCode"
                  :label="item.dictLabel"
                  :value="item.dictCode"
                  :disabled="item.status === 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="分类状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="强弱电类型">
              <el-radio-group v-model="form.onlineType">
                <el-radio
                  v-for="item in onlineTypeOptions"
                  :key="item.value"
                  :label="item.value"
                  @change="onlineTypeChange"
                >{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="离线时间">
              <el-input-number v-model="form.onlineTime" controls-position="right" :min="0" :step="10"/>
              <span style="font-weight: bold">分</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="备注" prop="categoryName">
              <el-input v-model="form.remark" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addDept,
  delDept, exportProductCategory,
  getDept,
  listCategoryExcludeChild,
  listProductCategory,
  updateDept
} from '@/api/system/deviceCategory'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getNodeById, getOrderNumOfNode } from '@/utils/ruoyi'

export default {
  name: 'Dept',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 表格树数据
      productCategoryTree: [],
      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      onlineTypeOptions: [{ label: '强电', value: '1' }, { label: '弱电', value: '2' }, { label: '其他', value: '3' }],
      // 产品功能字典
      productFunctionOptions: [],
      // 所选择的功能字典ID列表
      selectedDictList: [],
      // 查询参数
      queryParams: {
        categoryNum: undefined,
        categoryName: undefined,
        status: undefined
      },
      // 表单参数
      form: { dictCodeList: [] },
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: '上级分类不能为空', trigger: 'blur' }
        ],
        categoryNum: [
          { required: true, message: '分类编号不能为空', trigger: 'blur' }
        ],
        orderNum: [
          { required: true, message: '菜单顺序不能为空', trigger: 'blur' }
        ],
        email: [
          {
            type: 'email',
            message: '\'请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    selectedDictList(value) {
      this.form.dictCodeList = value.join(',')
    }
  },
  created() {
    this.getDictDataByType('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
    this.getDictDataByType('sys_product').then(response => {
      this.productFunctionOptions = response.data
      this.getList()
    })
  },
  methods: {
    /** 查询产品类型列表 */
    getList() {
      this.loading = true
      listProductCategory(this.queryParams).then(response => {
        let productCategoryList = response.data
        // 遍历productCategoryList, 给每个元素都加上dictLabelList
        for (let i = 0, len = productCategoryList.length; i < len; i++) {
          // 若该元素有字典值
          if (productCategoryList[i].dictCodeList) {
            let dictCodeListString = productCategoryList[i].dictCodeList
            if (dictCodeListString) {
              let dictCodeList = dictCodeListString.split(',')
              let dictLabelList = []
              // 遍历该元素的dictCodeList, 为其添加dictLabelList
              for (let j = 0, len2 = dictCodeList.length; j < len2; j++) {

                let dictData = this.productFunctionOptions.find(item => {
                  return item.dictCode === parseInt(dictCodeList[j])
                })

                if (dictData) {
                  dictLabelList.push(dictData.dictLabel)
                }
              }
              // 元素添加dictLabelList
              productCategoryList[i].dictLabelList = dictLabelList
            }
          } else {
            productCategoryList[i].dictLabelList = []
          }
        }

        this.productCategoryTree = this.handleTree(response.data, 'categoryId')
        this.deptOptions = this.handleTree(response.data, 'categoryId')
        this.loading = false
      })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.categoryId,
        label: node.categoryNum,
        children: node.children
      }
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        categoryId: undefined,
        parentId: undefined,
        categoryName: undefined,
        orderNum: undefined,
        leader: undefined,
        dictCodeList: [],
        status: '0',
        onlineType: '3',
        onlineTime: 0
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.selectedDictList = []
      this.reset()
      if (row !== undefined) {
        this.form.parentId = row.categoryId
      }

      this.deptOptions = JSON.parse(JSON.stringify(this.productCategoryTree))

      this.open = true
      this.title = '添加分类'

      if (this.form.parentId) {
        let parentNode = getNodeById(this.productCategoryTree, 'categoryId', this.form.parentId)
        this.form.orderNum = getOrderNumOfNode(parentNode)
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      // 取出该数据的dictCodeList, 将其赋给this.selectedDictList
      if (row.dictCodeList) {
        let strList = row.dictCodeList.split(',')
        let intList = []
        for (let i = 0, len = strList.length; i < len; i++) {
          intList.push(parseInt(strList[i]))
        }
        this.selectedDictList = intList
      } else {
        this.selectedDictList = []
      }

      getDept(row.categoryId).then(response => {
        // 填充表单数据
        this.form = response.data
        this.open = true
        this.title = '修改产品类型信息'
      })
      listCategoryExcludeChild(row.categoryId).then(response => {
        this.deptOptions = this.handleTree(response.data, 'categoryId')
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.categoryId !== undefined) {
            updateDept(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addDept(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.categoryName + '"的数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delDept(row.categoryId)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },

    /**
     * 所选离线类型改变时, 修改默认的离线时间
     */
    onlineTypeChange(value) {
      if (value === '1') {
        this.form.onlineTime = 130
      } else if (value === '2') {
        this.form.onlineTime = 490
      } else {
        this.form.onlineTime = 0
      }
    },

    /**
     * 对话框确认关闭
     */
    closeDialogConfirm() {
      this.$confirm('确认关闭?').then(() => {
        this.open = false
      }).catch(() => {
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return exportProductCategory(this.queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    }
  }
}
</script>
